package com.itheima.wisdomnext.controller;

import com.itheima.wisdomnext.entity.Announcement;
import com.itheima.wisdomnext.entity.Result.ResponseResult;
import com.itheima.wisdomnext.service.AnnouncementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/api/announcements")
public class AnnouncementController {

    @Autowired
    private AnnouncementService announcementService;

    /**
     * 获取所有公告列表
     * @return 包含所有公告的响应数据
     */
    @GetMapping("/all")
    public ResponseEntity<ResponseResult<List<Announcement>>> getAllAnnouncements() {
        List<Announcement> announcements = announcementService.getAllAnnouncements();
        return ResponseEntity.ok(ResponseResult.success("获取所有公告成功！", announcements));
    }

    /**
     * 根据公告 ID 获取单个公告内容
     * @param id 公告 ID
     * @return 公告详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<ResponseResult<Announcement>> getAnnouncementById(@PathVariable Integer id) {
        Announcement announcement = announcementService.getAnnouncementById(id);
        return ResponseEntity.ok(ResponseResult.success("获取公告成功！", announcement));
    }

    /**
     * 发布公告（支持上传附件）
     * @param announcement 公告对象，包含标题、内容等字段（JSON 格式）
     * @return 发布结果
     */
    @PostMapping("/create")
    public ResponseEntity<ResponseResult<Void>> createAnnouncement(
            @RequestBody Announcement announcement  // 接收 JSON 数据
    ) throws Exception {
        announcementService.createAnnouncement(announcement);
        return ResponseEntity.ok(ResponseResult.success("公告发布成功！", null));
    }

    /**
     * 更新公告信息
     * @param announcement 公告对象（更新后的数据）
     * @return 更新结果
     */
    @PutMapping("/update")
    public ResponseEntity<ResponseResult<Void>> updateAnnouncement(@RequestBody Announcement announcement) throws Exception{
        announcementService.updateAnnouncement(announcement);
        return ResponseEntity.ok(ResponseResult.success("公告更新成功！", null));
    }

    /**
     * 将公告标记为“失效”（软删除）
     * @param id 公告 ID
     * @return 操作结果
     */
    @PutMapping("/deactivate/{id}")
    public ResponseEntity<ResponseResult<Void>> deactivateAnnouncement(@PathVariable Integer id) throws Exception{
        announcementService.deactivateAnnouncement(id);
        return ResponseEntity.ok(ResponseResult.success("公告已成功标记为失效！", null));
    }
}
